from ntpath import join
import re
from typing_extensions import final
from flask import Blueprint, json,request,jsonify
import json
from db import db1
import jinja2
from qiniu import Auth
from werkzeug import datastructures


bp_course = Blueprint('course',__name__)



access_key = 'pUQVI-IdCIbvwQL7SoOFLBNTvsKrOzEJHzi2jSMf'
secret_key = 'MrlAco_0VgbVfNGbDXOfm1aG8V3OSuaU1Ls7ULZw'
@bp_course.route('/qntoken')
def qntoken():
    q = Auth(access_key, secret_key)
    # 要上传的空间
    bucket_name = '2104'
    # 生成上传 Token
    token = q.upload_token(bucket_name)
    return jsonify({"token":token})


#无限级分类重构
def xtree(data):
    #先判断data没有直接返回
    if not data:
        return data
    #遍历data变成字典
    tree={}
    list=[]
    for i in data:
        tree[i['id']] = i
    
    for j in data:
        #获取父id
        pid = j['pid']
        if pid == 0:
            #说明顶级分类直接加入列表
            list.append(j)
        else:
            #查看父类下有没有子类
            if 'son' not in tree[pid]:
                #如果没有初始化列表
                tree[pid]['son'] = []
            #把子类加到父类列表中
            tree[pid]['son'].append(j)
    return list

@bp_course.route('/cateM',methods=['POST','GET'])
def cateM():
    if request.method == 'POST':
        #添加
        #获取数据
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        #构造sql
        sql = "insert into cates values(0,'%s',%d,%s)"%(data['name'],int(data['pid']),data['params'])
        print(sql)
        #调用db1
        db1.update(sql)
        #返回结果
        return jsonify({"code":200})
    else:
        #无限级分类展示
        sql = "select * from cates"
        res = db1.findall(sql)
        data = xtree(res)
        return jsonify({"code":200,'list':data})


@bp_course.route('/pagecates')
def pagecates():
    #每页面显示多少条
    page_size=2
    #当前页
    page = request.args.get('page')
    start = (int(page)-1)*page_size
    sql = "select * from cates  order by id asc limit %d,%d"%(start,page_size)
    # sql = "select c.name,c.params,t.name as tname from cates as c left join cates as t on c.pid=t.id order by c.id desc"
    res = db1.findall(sql)
    #查询共有多少条记录
    sql1 = "select count(id) as total from cates"
    res1 = db1.find(sql1)
    return jsonify({"code":200,'list':res,'total':res1['total']})


@bp_course.route('/getCateByid')
def getCateByid():
    id = request.args.get('id')
    sql = "select params from cates where id=%d"%(int(id))
    res = db1.find(sql)
    return jsonify({'code':200,'params':res['params']})


@bp_course.route('/courseM',methods=['POST','GET'])
def courseM():
    if request.method=='POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        if data['params']:
            sql = "insert into courses(title,pid,params,pic,descrip,teacher_id,status) values('%s',%d,'%s','%s','%s',%d,%d)"%(data['title'],int(data['pid']),data['params'],data['pic'],data['descrip'],int(data['teacher_id']),int(data['status']))
        else:
            sql = "insert into courses(title,pid,pic,descrip,teacher_id,status) values('%s',%d,'%s','%s',%d,%d)"%(data['title'],int(data['pid']),data['pic'],data['descrip'],int(data['teacher_id']),int(data['status']))
    
        db1.update(sql)
        return jsonify({'code':200})
    else:
        try:
            page = int(request.args.get('page'))
        except:
            page=0
        if page:
            page_size=2
            start = (page-1)*page_size
            sql = "select cates.name,courses.pic,courses.title from courses left join cates on courses.pid=cates.id limit %d,%d"%(start,page_size)
            res = db1.findall(sql)
        else:
            sql = "select * from courses"
            res= db1.findall(sql)
        sql1 = "select count(id) as count from courses"
        total = db1.find(sql1)
        return jsonify({'code':200,'list':res,'total':total['count']}) 


import os  
@bp_course.route('/vedioupload',methods=['POST'])
def vedioupload():
    file = request.files['file']
    course_id  = request.form['course_id']
    path = './static/upload'+'/'+str(course_id)
    if not os.path.exists(path):
        os.mkdir(path)
    file.save(os.path.join(path,file.filename))
    return jsonify({'code':200,'url':'/static/upload'+'/'+str(course_id)+'/'+file.filename})

#添加章节接口
@bp_course.route('/jieM',methods=['POST','GET'])
def jieM():
    if request.method == "POST":
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = "insert into jie(name,course_id,video_url) values('%s',%d,'%s')"%(data['name'],int(data['course_id']),data['vedio_url'])
        print(sql)
        db1.update(sql)
        return jsonify({"code":200})



# 活动
@bp_course.route('/activeM',methods=['POST','GET'])
def activeM():
    if request.method=='POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = "insert into active(title,titlename,address,stime,total_time,t_count,price) values('%s','%s','%s','%s','%s',%d,%.1f)"%(data['title'],data['titlename'],data['address'],data['stime'],data['total_time'],int(data['t_count']),float(data['price']))
        db1.update(sql)
        return jsonify({'code':200})
    else:
        sql = "select * from active"
        res = db1.findall(sql)
        return jsonify({'code':200,'list':res})


@bp_course.route('/activeRM',methods=['POST','GET'])
def activeRM():
    if request.method=='POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = "select * from active_record where mobile='%s and active_id=%d'"%(data['mobile'],int(data['active_id']))
        res = db1.find(sql)
        if res:
            return jsonify({'code':20011,'mes':'您已经报名过，不能在报名'})
        # 根据手机号查询用户表
        sql1 = "select * from activer where mobile='%s'"%(data['mobile'])
        res1 = db1.find(sql1)
        sql2 = "select * from active where id=%d"%(int(data['active_id']))
        res2 = db1.find(sql2)
        # 找到用户,判断用户等级为3
        if res1:
            if res1['type']==3:
                # 可以加入活动订单表
                bb = "insert into active_record(active_id,mobile,type,pay_status,price) values(%d,'%s',1,2,0)"%(int(data['active_id']),data['mobile'])
                db1.update(bb)
                sql5 = "select * from active_record where mobile='%s and active_id=%d'"%(data['mobile'],int(data['active']))
                res5 = db1.find(sql5)
                if int(res2['use_count'])>=1:
                    count = int(res2['use_count'])
                    sql3= "update active set use_count=%d where id=%d"%(count,int(data['active_id'])) 
                    db1.update(sql3)
                    return jsonify({'code':200,'money':res5['price'],'order_id':res5['id']})
                else:
                    return jsonify({'code':20015,'mes':'数量不够'})
                    
            else:
                return jsonify({'code':30010,'mes':'您无权参加'})
        else:
            # 没有找到，是新用户
            acsql = "insert into active_record(mobile,active_id,type,pay_status,price) values('%s',%d,2,1,%.1f)"%(data['mobile'],int(data['active_id']),float(res2['price']))
            db1.update(acsql)
            sql4 = "select * from active_record where mobile='%s' and active_id=%d"%(data['mobile'],int(data['active_id']))
            res4= db1.find(sql4)
            return jsonify({'code':200,'order_id':res4['id'],'money':res4['price']})


@bp_course.route('/getcourses')
def getcourses():
    id = request.args.get('id')
    
    sql="select * from courses where id=%d"%(int(id))
    res = db1.find(sql)
    sql2 = "select * from jie where course_id=%d order by sort asc"%(int(id))
    res2 = db1.findall(sql2)
    res['jielist']=res2
    # 默认没关注
    res['follow']=False
    # 查询用户是否关注课程
    try:
        userid = request.args.get('userid')
        sql4 = "select * from user_follow_course where userid=%d and courseid=%d"%(int(userid),int(id))
        res4 = db1.find(sql4)
        if res4:
            res['follow']=True
    
    except:
        pass
    return jsonify({'code':200,'list':res,'follow':res['follow']})
    



# @bp_course.route('/premession')
# def premession():
#     userid = request.args.get('userid')
#     courseid = request.args.get('courseid')
    # sql = "select level from users where id=%d and "%(int(userid))
    # res=db1.find(sql)


# @bp_course.route('/teacher')
# def teacher():
#     id = request.args.get('id')
#     page = request.args.get('page')
#     page_size=2
#     start = (int(page)-1)*page_size
#     sql = "select id title from courses where teacher_id=%d limit %d,%d"%(int(id),start,page_size)
#     res = db1.findall(sql)
#     sql1 = "select count(id) as t  from courses where teacher_id=%d"%(int(id))
#     res1 = db1.findall(sql1)
#     return jsonify({'code':200,'list':res,'total':res1['t']})


@bp_course.route('/user_follow')
def user_follow():
    courseid=request.args.get('id')
    userid=request.args.get('userid')
    type = int(request.args.get('type'))
    if type==1:
        sql = "select * from user_follow_course where userid=%d and courseid=%d"%(int(userid),int(courseid))
        res = db1.find(sql)
        if res:
            return jsonify({'code':10030,'mes':'你已经关注了'})
        sql1 = "insert into user_follow_course(userid,courseid) values(%d,%d)"%(int(userid),int(courseid))
        db1.update(sql1)
        mes='关注成功'
    else:
        sql2 = "delete from user_follow_course where userid=%d and courseid=%d"%(int(userid),int(courseid))
        db1.update(sql2)
        mes='取消关注'
    csql = "select follow_count from courses where id=%d"%(int(courseid))
    res1 = db1.find(csql)
    
    count = int(res1['follow_count'])
    if type==1:
        count=1
    else:
        if count>=1:
            count-=1
    sql3 = "update courses set follow_count=%d where id=%d"%(count,int(courseid))
    print(sql3)
    db1.update(sql3)
    return jsonify({'code':200,'mes':mes})



# import pymongo
# @bp_course.route('/test')
# def test():
#     data = request.form
#     conn = pymongo.MongoClient(host='localhost',port='27017')
#     db = conn.student


@bp_course.route('/hezuo',methods=['POST'])
def hezuo():
    data = request.data
    if data:
            data = json.loads(data)
    else:
            data = request.form
    print(data)
    sql = "insert into hezuoshang(name,code,price,pic) values('%s','%s',%.2f,'%s')"%(data['name'],data['code'],float(data['price']),data['pic'])
    db1.update(sql)
    return jsonify({'code':200})